package com.sr.service.impl;

import com.sr.constant.Constant;
import com.sr.enums.ResponseCode;
import com.sr.exception.Assert;
import com.sr.exception.BusinessException;
import com.sr.ibase.IBaseService;
import com.sr.pojo.WMember;
import com.sr.service.ILoginService;
import com.sr.service.IMemberService;
import com.sr.util.BCrypt;
import com.sr.util.JwtTokenUtil;
import com.sr.util.RedisUtil;
import com.sr.util.ToolUtil;
import com.sr.vo.req.LoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author xiaochi
 * @date 2022/5/1 11:59
 * @desc LoginServiceImpl
 */
@Service
@RequiredArgsConstructor(onConstructor = @__)
public class LoginServiceImpl implements ILoginService {

    private final IMemberService memberService;


    /**
     * 登录
     * @param loginVo
     * @return
     */
    @Override
    public LoginVo login(LoginVo loginVo) {
        IBaseService.Criteria<WMember> criteria = memberService.createCriteria(WMember.class);
        criteria.andEqualTo(WMember::getUsername,loginVo.getUsername())
                .andNotEqualTo(WMember::getIsDel,0);
        WMember member = memberService.findOne(criteria);
        Assert.assertNotNull(member,new BusinessException(ResponseCode.SYSTEM_USERNAME_NOT_EXISTS));
        Assert.isTure(!Objects.equals(member.getIsDel(),2),new BusinessException(ResponseCode.SYSTEM_USERNAME_DISABLED));
        Assert.isTure(BCrypt.checkpw(loginVo.getPassword(),member.getPassword()),new BusinessException(ResponseCode.SYSTEM_PASSWORD_ERROR));
        member.setPassword(null);
        Map<String,Object> map = new HashMap<>();
        map.put(Constant.User.JWT_USERNAME,member.getUsername());
        String token = JwtTokenUtil.generateToken(member.getId(), map);
        LoginVo loginResVo = ToolUtil.copy(member, LoginVo.class);
        loginResVo.setAuthorization(token);
        RedisUtil.set(Constant.User.USER_TOKEN_KEY+member.getId(),token);
        RedisUtil.hput(Constant.User.USER_KEY,member.getId(),member,Constant.User.USER_KEY_EXPIRE);
        return loginResVo;
    }

    /**
     * 退出登录
     * @param token
     * @param userId
     */
    @Override
    public void logout(String token, String userId) {
        RedisUtil.del(Constant.User.USER_TOKEN_KEY+userId);
        RedisUtil.hdel(Constant.User.USER_KEY,userId);
    }
}
